package com.ruoyi.framework.security.context;

import com.ruoyi.framework.security.wx.WxAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WxAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {


    public WxAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher("/sso/login", "GET"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        String ticket = httpServletRequest.getParameter("ticket");

        WxAuthenticationToken authenticationToken = new WxAuthenticationToken(ticket, null);

        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        return this.getAuthenticationManager().authenticate(authenticationToken);

    }
}